# coding=utf8
#region import
import itchat
from itchat.content import *
import socket
import sys
import json
from bottle import route, run, request
import datetime
import urllib
import sys
import urllib2
import json
import threading
import random
import codecs
import string
import os
#endregion
reload(sys)
sys.setdefaultencoding('utf8')

local_web_server_port=19990
remote_web_server_port=19991
remote_web_ip="127.0.0.1"
sys_commnad_list=[]
log_file_dir="log"

#启动Web服务器
def web_server_start():
    my_thread = threading.Thread(target=thread_web_server, args=())
    my_thread.setDaemon(True)
    my_thread.start()

# Web服务器启动线程
def thread_web_server():
    global web_server_port
    run(host='0.0.0.0', port=local_web_server_port, debug=True)

#region Web 服务器，控制程序发来的POST方法
@route('/', method='POST')
def response_post():
    global  sys_commnad_list
    data = {
        'method': 'POST',
        'location': 'Server',
        'result': 'OK',
        'datetime': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    faild_data = {
        'method': 'POST',
        'location': 'Server',
        'result': 'FAILD',
        'datetime': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    print request.json
    result=json.dumps(faild_data)

    try:
        if request.json['action']==u'Test':
            return json.dumps(data)
    except:
        pass

    command=request.json['cmd']
    data_0=request.json['data_0']
    data_1=request.json['data_1']
    data_2=request.json['data_2']
    data_3=request.json['data_3']
    for f in sys_commnad_list:
        if f[0]==command:
            if data_0==u'':
                result=f[1]()
                break
            if data_1==u'':
                result=f[1](data_0)
                break
            if data_2==u'':
                result=f[1](data_0,data_1)
                break
            if data_3==u'':
                result=f[1](data_0,data_1,data_2)
                break
            result = f[1](data_0, data_1, data_2,data_3)

    # post_to_remote_server(result)
    write_log(json.dumps(result,indent=2),prefix=command)
    return json.dumps(result)
#endregion

#region Web 服务器，控制程序发来的GET方法
# 由对方检测，确定服务器正常运行
@route('/', method='GET')
def response_get():
    data = {
        'method': 'GET',
        'location': 'Server',
        'result': 'OK',
        'datetime': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    return json.dumps(data)
#endregion

# 以随机的文件名写日志
def write_log(msg,prefix=""):
    # 生成随机字符串作为新文件名
    if(os.path.exists(log_file_dir)==False):
        os.mkdir(log_file_dir)

    new_name = ''.join((random.choice(string.ascii_letters) for i in range(random.randint(5, 20))))
    f = codecs.open(u'%s/%s_%s.txt' % (log_file_dir,prefix,new_name), "w", "utf-8")
    txt = (u'%s' % msg)
    f.write(txt)
    f.close()

# 向远程服务器发送微信服务器发来的信息
def post_to_remote_server(msg):
    json_msg=json.dumps(msg,indent=2)
    write_log(json_msg)
    global remote_web_ip
    global remote_web_server_port
    headers = {'Content-Type': 'application/json'}
    url=u'http://%s:%s/'%(remote_web_ip,remote_web_server_port)
    request = urllib2.Request(url, headers=headers, data=u'%s'%json_msg)
    response = urllib2.urlopen(request)
    return response.read()

#其他用户单独发过来的消息
@itchat.msg_register([TEXT,SHARING])
def text_reply(msg):
    # 如果是其他管理员发送的
    post_to_remote_server(msg)

# 接收群内用户发送的文本信息
@itchat.msg_register(TEXT, isGroupChat=True)
def group_text_reply(msg):
    post_to_remote_server(msg)

@itchat.msg_register(FRIENDS)
def add_friend(msg):
    post_to_remote_server(msg)
    itchat.add_friend(**msg['Text']) # 该操作会自动将新好友的消息录入，不需要重载通讯录
    itchat.send_msg('很高兴在微信上认识，有缘人啊！', msg['RecommendInfo']['UserName'])

#接收到的消息
def sys_commnad_init():
    global  sys_commnad_list
    sys_commnad_list=[]
    sys_commnad_list.append(['get_friends',itchat.get_friends])
    sys_commnad_list.append(['get_contact',itchat.get_contact])
    sys_commnad_list.append(['get_chatrooms',itchat.get_chatrooms])
    sys_commnad_list.append(['get_head_img',itchat.get_head_img])
    sys_commnad_list.append(['get_mps',itchat.get_mps])

    sys_commnad_list.append(['update_chatroom',itchat.update_chatroom])
    sys_commnad_list.append(['update_friend',itchat.update_friend])

    sys_commnad_list.append(['set_alias',itchat.set_alias])
    sys_commnad_list.append(['set_pinned',itchat.set_pinned])
    sys_commnad_list.append(['set_chatroom_name',itchat.set_chatroom_name])

    sys_commnad_list.append(['add_friend',itchat.add_friend])
    sys_commnad_list.append(['add_member_into_chatroom',itchat.add_member_into_chatroom])

    sys_commnad_list.append(['create_chatroom',itchat.create_chatroom])

    sys_commnad_list.append(['delete_member_from_chatroom',itchat.delete_member_from_chatroom])

    sys_commnad_list.append(['send_raw_msg',itchat.send_raw_msg])
    sys_commnad_list.append(['send_msg',itchat.send_msg])
    sys_commnad_list.append(['send_file',itchat.send_file])
    sys_commnad_list.append(['send_image',itchat.send_image])
    sys_commnad_list.append(['send_video',itchat.send_video])
    sys_commnad_list.append(['send',itchat.send])

    sys_commnad_list.append(['upload_file',itchat.upload_file])

    sys_commnad_list.append(['dump_login_status',itchat.dump_login_status])

    sys_commnad_list.append(['search_friends',itchat.search_friends])

    sys_commnad_list.append(['search_chatrooms',itchat.search_chatrooms])
    sys_commnad_list.append(['search_mps',itchat.search_mps])


#启动系统
def sys_init():
    web_server_start()
    sys_commnad_init()



itchat.auto_login(True)
sys_init()
itchat.run()